package com.请求对象;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.Map;
import java.util.Set;

@WebServlet("/demo4")
public class 反射分装 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Student stu = new Student();
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<String> keys = parameterMap.keySet();
        for (String key : keys) {
            try {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(key, stu.getClass());
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (parameterMap.get(key).length != 1) {
                    writeMethod.invoke(stu, (Object) parameterMap.get(key));
                } else {
                    writeMethod.invoke(stu, parameterMap.get(key));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(stu);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
